﻿// //  ********************************************************************************
// //  Copyright (C) 2016 Sebastian Kenter. All rights reserved.
// // 
// //  Name    : MultiServerEngine | ServerFramework | SessionManager.cs
// //  Created : 2016 - 02 - 16 20:53
// //  Modified: 2016 - 02 - 20 12:32
// //  ********************************************************************************

using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;

namespace ServerFramework.Implementation.Database
{
    /// <summary>
    ///     Small, simple session manager class which initializes NHibernate's session factory and loads the
    ///     configuration.
    /// </summary>
    public class SessionManager
    {
        #region Class Property Declarations

        /// <summary>Gets the session factory created from the initialized configuration. The returned factory is thread safe.</summary>
        private static ISessionFactory _sessionFactory { get; }

        #endregion

        #region Class Member Declarations

        public static ISessionFactory SessionFactory => _sessionFactory;

        #endregion

        static SessionManager()
        {
            _sessionFactory = Fluently.Configure()
                .Database(MySQLConfiguration.Standard
                    .ConnectionString(
                        c =>
                            c.Server(DBSettings.Default.DBHostConf)
                                .Database(DBSettings.Default.DBSchemaConf)
                                .Username(DBSettings.Default.DBUserConf)
                                .Password(DBSettings.Default.DBPassConf)))
                .Mappings(m => m.FluentMappings.AddFromAssembly(typeof (SessionManager).Assembly))
                .BuildSessionFactory();
        }

        /// <summary>Opens a new session on the existing session factory</summary>
        /// <returns>ready to use ISession instance</returns>
        /// <remarks>
        ///     Dispose this instance after you're done with the instance, so after lazy loading has occurred. The returned
        ///     ISession instance is <b>not</b> thread safe.
        /// </remarks>
        public static ISession OpenSession()
        {
            return _sessionFactory.OpenSession();
        }
    }
}
